import { defineStore } from 'pinia';

export type OutputLine = { ts: number; text: string };

export interface OutputChannel {
	name: string;
	lines: OutputLine[];
}

export interface OutputState {
	activeChannel: string;
	channels: Record<string, OutputChannel>;
}

function ensureChannel(state: OutputState, name: string): OutputChannel {
	if (!state.channels[name]) {
		state.channels[name] = { name, lines: [] };
	}
	return state.channels[name];
}

export const useOutputStore = defineStore('output', {
	state: (): OutputState => ({
		activeChannel: 'General',
		channels: {},
	}),
	actions: {
		setActiveChannel(name: string) {
			this.activeChannel = name;
			ensureChannel(this, name);
		},
		append(name: string, text: string) {
			const chan = ensureChannel(this, name);
			const chunks = String(text || '').split(/\r?\n/);
			const now = Date.now();
			for (const c of chunks) {
				if (c === '') continue;
				chan.lines.push({ ts: now, text: c });
			}
		},
		clear(name?: string) {
			if (!name) {
				for (const k of Object.keys(this.channels)) this.channels[k].lines = [];
				return;
			}
			ensureChannel(this, name).lines = [];
		},
	},
});


